package com.service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.eclipsesource.v8.V8;

public class CookieService {
	/*<html><body><script language="javascript"> 
	 * window.onload=setTimeout("mq(222)", 200); 
	 * function mq(RD) {......;eval("qo=eval;qo(po);");} 
	 * </script> </body></html>
	 */
	public static String parseCookie(String html){
		html = html.replaceAll("</script.*","");
		V8 runtime = V8.createV8Runtime();
		String result = null;
		//创建JS代码运行环境
		String function = patternFunction(html);
		String js = html.replaceFirst(".*?;",function+";");
		js = js.replaceAll("eval\\(\".*?\"\\);","return po;");
		synchronized (runtime) {
			result=runtime.executeStringScript(js);
			result = patternCookie(result);
			//释放运行环境
			runtime.release();
		}
		return result;
	}
	
	public static String patternCookie(String str){
		String matstr = null;
		String regEx = "'.*'";
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(str);
		if(mat.find()){
			matstr = mat.group();
			matstr = matstr.replaceAll("'","");
		}
		return matstr;
	}
	
	public static String patternFunction(String str){
		String matstr = null;
		String regEx = "\\(.*?\\)";
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(str);
		if(mat.find()){
			matstr = mat.group();
			matstr = matstr.replaceAll("\\(\"","");
		}
		return matstr;
	}
	
	
}
